import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(request: NextRequest) {
  try {
    const projects = await db.project.findMany({
      include: {
        _count: {
          select: {
            requirements: true,
            tasks: true,
            bugs: true,
            members: true
          }
        }
      },
      orderBy: { createdAt: 'desc' }
    })

    return NextResponse.json(projects)
  } catch (error) {
    console.error('Error fetching projects:', error)
    return NextResponse.json(
      { error: 'Failed to fetch projects' },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { name, key, description, type } = body

    if (!name || !key) {
      return NextResponse.json(
        { error: 'Missing required fields: name and key are required' },
        { status: 400 }
      )
    }

    // Check if project key already exists
    const existingProject = await db.project.findUnique({
      where: { key }
    })

    if (existingProject) {
      return NextResponse.json(
        { error: 'Project with this key already exists' },
        { status: 400 }
      )
    }

    const project = await db.project.create({
      data: {
        name,
        key,
        description,
        type: type || 'SOFTWARE',
        status: 'ACTIVE'
      },
      include: {
        _count: {
          select: {
            requirements: true,
            tasks: true,
            bugs: true,
            members: true
          }
        }
      }
    })

    return NextResponse.json(project, { status: 201 })
  } catch (error) {
    console.error('Error creating project:', error)
    return NextResponse.json(
      { error: 'Failed to create project' },
      { status: 500 }
    )
  }
}